package me.duyu.tools.handler

import io.vertx.ext.web.RoutingContext
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import kotlinx.coroutines.experimental.launch
import io.vertx.kotlin.coroutines.*

fun listClients(context: RoutingContext)
{
    val res = context.response()
    context.vertx().fileSystem().readDir("./clients"){
        when(it.succeeded()){
            false -> {
                res.statusCode = 403;
                res.end(it.toString());
            }
            true -> {
                val list = it.result()
                val array = JsonArray()
                for(str in list)
                    array.add(str)
                val obj = JsonObject()
                obj.put("data", list)
                res.statusCode = 200
                res.end(obj.encode())
            }
        }
    }
}

fun listClients2(context: RoutingContext)
{
    val res = context.response()
    launch (context.vertx().dispatcher()){
        try {
            val list = awaitResult<List<String>> {
                context.vertx().fileSystem().readDir("./clients",it)
            }
            val array = JsonArray()
            list.forEach { array.add(it)}
            val obj = JsonObject()
            obj.put("data", list)
            res.statusCode = 200
            res.end(obj.encode())
        } catch (e : Exception){
            res.statusCode = 403
            res.end(e.toString())
        }
    }
}

fun infoClient(context: RoutingContext)
{
    val res = context.response()
    val name = context.request().getParam("name")
    when(name.isNullOrEmpty()){
        true -> {
            res.statusCode = 403;
            res.end("NAME is null")
        }
        false -> {
            res.sendFile("./clients/$name")
        }
    }
}